package com.fly.service;

import com.fly.domain.User;
import com.fly.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * @author Fly
 * @Description
 * @Date Created in 8:29 2018/1/25
 * @Modified by
 */
@Service
public class UserService extends CurdService<UserRepository,User> implements UserDetailsService{

    @Autowired
    private UserRepository userRepository;
    /**
     * 删除用户
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeUsers(String ids){
        Arrays.asList(ids.split(",")).forEach(s -> UserService.super.delete(Long.valueOf(s)));
    }

    /**
     * 保存用户
     * @param user
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public User saveUser(User user){
        if(user.getIsNewRecord()){
            String password = new BCryptPasswordEncoder().encode(user.getPassword());
            user.setPassword(password);
        }
        return super.save(user);
    }

    /**
     * 根据用户名查找
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不对");
        }
        return user;
    }
}
